package com.wjp.banquet.common.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.cors.CorsUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CrosFilter implements Filter {

	Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
         throws IOException, ServletException {
        HttpServletRequest httpServletRequest =(HttpServletRequest)request;
        HttpServletResponse  httpServletResponse = (HttpServletResponse) response;
        if(CorsUtils.isCorsRequest((httpServletRequest))){
            //跨域  前端发送请求  前端要将withCredentials设为true  后端：httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
            //同时跨的域也要写成指定的，不能是*  如果不这样做，会有session id每次请求都是新的  如果不这样写，可以使用jwt来做用户登陆，因为jwt和session id无关
            //httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            String origin = httpServletRequest.getHeader("Origin");
            if(origin!=null&&!origin.trim().isEmpty()){
                if(origin.contains("127.0.0.1")
                        ||origin.contains("localhost")
                        ||origin.contains("xxx.com")
                ){
                    httpServletResponse.setHeader("Access-Control-Allow-Origin", origin);
                }
            }
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
            httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, client_id, uuid, Authorization");
            httpServletResponse.setHeader("Cache-Control", "no-store"); //
            httpServletResponse.setHeader("Pragma", "no-cache"); // 支持HTTP 1.0. response.setHeader("Expires", "0"); 
            httpServletResponse.setHeader("Access-Control-Expose-Headers","Content-Disposition");//下载文件用
            if("OPTIONS".equalsIgnoreCase(httpServletRequest.getMethod())){
                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                return;
            }
        }
        httpServletResponse.setHeader("Cache-Control", "no-store"); //
        httpServletResponse.setHeader("Expires", "0"); //
        chain.doFilter(request, httpServletResponse);
    }

}
